// pages/find_info/index.js
var t = getApp(),
  e = t.requirejs("api/index"),
  core = t.requirejs("core"),
  wxParse = t.requirejs("wxParse/wxParse");

Page({
  data: {
    route: "find_info",
    menu: t.tabBar,
    menu_show: false,
    show: false,
    display: false,
    use_wxParse: true,
    dobuy: false,
    page: 1,
    now_sku: {},
    num: 1,
    nowprice: 0.00,
    skus: [],
    isinputing: false,
    isvip: true,
    samegroup: [],
    samegroupid:[],
    loaded: false,
    liked: false,
    isplay: false,
    invoking: false,
    duration: 0,
    currecttime: 0,
    timechanging: false,
    nowtime: "00:00",
    endtime: "00:00",
    bofang:false,
    currIndex: '-1'
  },
  //底部导航跳转
  menu_url: function(k) {
    core.menu_url(k, 2);
  },

  onGotUserInfo: function (q) {
    var that = this,
        cache = t.getCache("userinfo");

    // if (cache) {
    //     return;
    // }
    t.getUserInfo(q.detail.userInfo, function (res) {
      if (res != 1000) {
        var ucache = getApp().getCache("userinfo");
        if (ucache) {
          //var options = that.data.options;
          //that.getDetail(options)
          //getCurrentPages()[getCurrentPages().length - 1].onLoad();
          that.setData({
            display: false,
            //getPhoneAuth: getApp().globalData.getphone
          })
        }
      } else {
        that.setData({
          display: true
        })
      }

    }, q.detail.encryptedData, q.detail.iv);
  },

  // 授权获取用户信息判断
  authCheck: function () {
    var cache = getApp().getCache("userinfo");
    if (!cache.nickName && !cache.avatarUrl) {
      this.setData({
        display: true
      })
      return false;
    } else {
      this.setData({
        display: false
      })
      return true;
    }
  },

  // 取消登录
  cancel_auth: function () {
    this.setData({
      display: false
    })
  },

  onLoad: function(options) {
    var that = this;
      if (options && options.card_id) {
        t.globalData.card_id = options.card_id;
      }
      if (options != null && options != undefined) {
        that.setData({
          tabbar_index: options.tabbar_index ? options.tabbar_index : -1
        });
      }

    var cache = t.getCache("userinfo");
    if (!cache.nickName && !cache.avatarUrl) {
      getApp().authSwitch(function(res){
        if (res == 1) {
          that.setData({
            display: true
          })
        } else {
          if (cache) {
            that.setData({
              display: false
            })
          } else {
            that.setData({
              display: true
            })
          }
        }
      })
    }

      core.setting();
      that.setData({
        menu: getApp().tabBar
      })
      var key = t.isInArray(getApp().tabBar.list, that.data.route);
      if (key) {
        that.setData({
          menu_show: true
        })
      }
      if (that.data.tabbar_index >= 0) {
        that.setData({
          showtabbar: true,
        })
      }
      that.setData({
        id: options.id
      })
      that.getinfo();
      that.getlist();
      that.getallprice();
    getApp().userlog(1, '付费内容', 'paycontent_browse');
  },

  // 停止音频播放
  onUnload: function(options) {
    wx.getBackgroundAudioManager().stop();
    console.log("audio stop")
  },

  to_info: function(e) {
    var that = this,
      page=this.data.page,
      id = core.pdata(e).id;
    if (id) {
      this.setData({
        id: id,
        page:page,
        invoking: true,
        isplay:false
      })
      that.getinfo();
    }
  },
  inputing: function(e) {
    console.log(e);
    var isinputing = this.data.isinputing;
    console.log(isinputing);
    this.setData({
      isinputing: !isinputing
    })
  },

  dobuy: function(e) {
    console.log("buy",this.data.skus);
    if (this.data.skus.length > 0) {
      this.setData({
        dobuy: true
      })
    } else {
      core.alert("未添加资费,暂不可购买");
    }
  },
  hidebuy: function(e) {
    if (!this.data.isinputing) {
      this.setData({
        dobuy: false
      })
    }
  },
  choose_sku: function(e) {
    console.log(e,"夷陵老祖");
    var index = e.currentTarget.dataset.index;
    var sku = this.data.skus[index];
    var nowprice = (sku.price * this.data.num).toFixed(2);
    this.setData({
      now_sku: sku,
      nowprice: nowprice
    })
  },
  num_change: function(e) {
    console.log(e);
    var num = e.detail.value;
    var nowprice = (this.data.now_sku.price * num).toFixed(2);
    this.setData({
      num: num,
      nowprice: nowprice
    })
  },

  tobuy: function(e) {
    var auth_res = this.authCheck();
    if (!auth_res) {
      return;
    }

    if (this.data.num <= 0) {
      core.error("购买数量必须大于0");
      return
    }
    this.setData({
      dobuy: false
    });
    core.loading("支付中...");
    var that = this;
    var data = {};
    data.content_id = this.data.detail.id;
    data.price_id = this.data.now_sku.id;
    data.type = this.data.now_sku.type;
    data.num = this.data.now_sku.num2 ? this.data.now_sku.num2:this.data.num;
    data.uid = t.getCache('userinfo').uid;
    data.openid = t.getCache("userinfo").openid;
    core.get("paycontent/createOrder", data, function(t) {
      if (0 == t.code) {
        wx.requestPayment({
          'timeStamp': t.info.timeStamp,
          'nonceStr': t.info.nonceStr,
          'package': t.info.package,
          'signType': 'MD5',
          'paySign': t.info.paySign,
          'success': function(res) {
            console.log(res)
            if (res.errMsg == "requestPayment:ok") {
              wx.showToast({
                title: "支付成功！",
                icon: "success",
                duration: 2000,
              })
              that.setData({
                page: 1
              })
              setTimeout(function() {
                that.getinfo();
                that.getlist();
                that.getallprice();
              }, 2000);
            } else {
              core.error('支付失败！');
            }
          },
          'fail': function(res) {
            core.error('您已经取消支付！')
          }
        })
      } else {
        core.error(t.msg)
      }
    });
  },
  play_music: function() {
    var that = this;
    console.log(that,"魏无羡")
    var title = this.data.detail.title;
    var coverImgUrl = this.data.detail.image;
    var src = this.data.detail.audio_url;
    if (src && src != '') {
      const backgroundAudioManager = wx.getBackgroundAudioManager();
      backgroundAudioManager.title = title
      backgroundAudioManager.coverImgUrl = coverImgUrl
      backgroundAudioManager.src = src
      this.setData({
        isplay: true
      });
      backgroundAudioManager.onCanplay(function(res) {
        console.log("onCanplay !!!!!!!!!");
      })
      backgroundAudioManager.onPlay(function(res) {
        console.log("onPlay !!!!!!!!!");
        that.setData({
          duration: parseInt(backgroundAudioManager.duration),
          endtime: that.timeformat(parseInt(backgroundAudioManager.duration))
        })
        // that.startAnimationInterval();
      })
      backgroundAudioManager.onEnded(function(res) {
        console.log("onEnded !!!!!!!!!");
        that.setData({
          currecttime: 0,
          isplay: false,
          nowtime: "00:00",
          bofang:true,
        })
      })
      backgroundAudioManager.onPause(function(res) {
        console.log("onPause !!!!!!!!!");
        that.setData({
          isplay: false,
        })
      })
      backgroundAudioManager.onTimeUpdate(function(res) {
        console.log("onTimeUpdate !!!!!!!!!");
        console.log("onTimeUpdate !!!!!!!!!",that.timeformat(parseInt(backgroundAudioManager.currentTime)));
        if (!that.data.timechanging) {
          that.setData({
            currecttime: parseInt(backgroundAudioManager.currentTime),
            nowtime: that.timeformat(parseInt(backgroundAudioManager.currentTime))
          })
        }
      })
    }
  },
  timeformat: function(time) {
    var m = parseInt(time / 60);
    m = m < 10 ? "0" + m : "" + m;
    var s = time % 60;
    s = s < 10 ? "0" + s : "" + s;
    return m + ":" + s;
  },
  timechanging: function(res) {
    this.setData({
      timechanging: true,
    })
  },
  timechange: function(res) {
    console.log("timechange !!!!!!!!");
    var time = res.detail.value;
    wx.getBackgroundAudioManager().seek(time);
    this.setData({
      currecttime: time,
      timechanging: false,
    })
  },
  play_status_change: function() {
    if (this.data.isplay) {
      wx.getBackgroundAudioManager().pause();
      this.setData({
        isplay: false,
        bofang:false,
      })
      
    } else  {
      if(this.data.bofang==true){
        this.play_music();
      }       
        wx.getBackgroundAudioManager().play();
        this.setData({
          isplay: true
        })
      
    }
  },
  onShow: function() {
    this.checkuser();
  },
  checkuser: function() {
    var that = this;
    var e = {};
    core.get("paycontent/checkuser", {
      uid: t.getCache('userinfo').uid != undefined ? t.getCache('userinfo').uid : 0,
    }, function(t) {
      if (t.code == 0) {
        e.isvip = t.info;
        that.setData(e);
      } else {
        a.alert(t.msg);
      }
    }, true)
  },
  dolike: function() {
    var that = this;
    var e = {};
    core.get("paycontent/dolike", {
      id: that.data.detail.id,
      uid: t.getCache('userinfo').uid != undefined ? t.getCache('userinfo').uid : 0,
    }, function(t) {
      if (t.code == 1) {
        e.liked = !that.data.liked;
        that.setData(e);
      } else {
        a.alert("收藏失败");
      }
    }, true)
  },
  getinfo: function() {
    var a = this,
        id = a.data.id,
        invoking = a.data.invoking;
    var e = {};
    core.get("paycontent/paycontent_info", {
      id: id,
      uid: t.getCache('userinfo').uid != undefined ? t.getCache('userinfo').uid : 0,
    }, function(t) {
      // 请求结束后调用
      if (invoking) {
        a.getlist();
        a.getallprice();
      }
      wx.setNavigationBarTitle({
        title: t.info.title ? t.info.title : '详情'
      })
      console.log("num",t);
      if (t.code == 0) {
        try {
          wxParse.wxParse("wxParseData", "html", t.info.content, a, "0");
          e.use_wxParse = true;
          //console.log("use wxParse !!!");
        } catch (err) {
          e.use_wxParse = false;
          //console.log("not use wxParse !!!");
        }
        e.detail = t.info;
        e.liked = t.info.liked;
        e.show = true;

        a.setData(e)
        console.log("content_info",a.data.detail);
        if (t.info.paycontent_type == 1) {
          a.play_music();
        }
      } else {
        core.alert(t.msg)
      }
    }, true)
  },
  getlist: function() {
    var a = this,
      id = a.data.id;
    var e = {};
    var page = a.data.page;
    console.log("page",page);
    core.get("paycontent/samegroup", {
      id: id,
      uid: t.getCache('userinfo').uid != undefined ? t.getCache('userinfo').uid : 0,
      page: page,
    }, function(t) {
      if (t.code == 0) {
        if (t.info.length > 0) {
          if (a.data.page == 1) {
            e.samegroup = t.info;
            e.samegroupid = t.info_id;
            e.page = page + 1;
          } else {
            e.page = a.data.page + 1;
            e.samegroup = a.data.samegroup.concat(t.info);
          }
        } else {
          e.loaded = true
        }
        a.setData(e);
      } else {
        core.alert(t.msg)
      }
    }, true)
  },
  getallprice: function() {
    var a = this,
      id = a.data.id;
    var e = {};
    core.get("paycontent/allprice", {
      id: id,
    }, function(t) {
      if (t.code == 0) {
        if (t.info.length > 0) {
          e.skus = t.info;
          e.now_sku = t.info[0];
          e.nowprice = t.info[0].price;
          a.setData(e);
        }
      } else {
        core.alert(t.msg)
      }
    }, true)
  },
  //上一首
  superior:function(){
    var that=this,
      array = that.data.samegroupid; 
    for (var index in array){
      if (that.data.id == array[index].id){
        that.setData({
          currIndex: index
        })
        break;
      }
    }
    var curr_index = that.data.currIndex - 1;
    var id = array[curr_index].id;
    var page=this.data.page;
    if (id) {
      this.setData({
        id: id,
        page: page,
        invoking: true
      })
      that.getinfo();
    }
    console.log(id, "id") 

    
  },
  //下一首
  next:function(){
    var that=this,
      array = that.data.samegroupid;
    for (var index in array) {
      console.log(index, "index")
      if (that.data.id == array[index].id) {
        that.setData({
          currIndex: index
        })
        break;
      }
    }
    var curr_index = parseInt(that.data.currIndex)  + 1;
    var id = array[curr_index].id;
    var page=this.data.page;
    if (id) {
      this.setData({
        id: id,
        page: page,
        invoking: true
      })
      that.getinfo();
    }
    console.log(id, "id") 
  },
  /**
   * 下拉刷新
   */
  onPullDownRefresh: function() {
    this.getinfo();
    wx.stopPullDownRefresh();
  },
  /**
   *上拉加载
   */
  onReachBottom: function() {
    console.log("上拉",this.data.loaded)
    
    // this.data.loaded || 
    this.getlist();
  },
  //分享
  onShareAppMessage: function() {
    // 暂停音乐播放
    wx.getBackgroundAudioManager().pause();

    // 记录用户操作，用于推送
    t.userlog(2, '付费内容', 'paycontent_relay');

    var title = this.data.detail.title;
    var path = '/yb_mingpian/pages/paycontent/info/index?id=' + this.data.detail.id + "&card_id=" + t.globalData.card_id;
    console.log(path)
    return {
      title: title,
      path: path
    }
  },
})